/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：SendMailServlet   
 * 类描述：    邮件发送接口
 * 创建人：zhangl  
 * 创建时间：2016年10月25日 上午11:34:44   
 * 修改人：zhangl   
 * 修改时间：2016年10月25日 上午11:34:44   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.CommFun;
import com.lst.dao.MstClientMapper;
import com.lst.dao.MstMessageMapper;
import com.lst.entity.request.MailReqPara;
import com.lst.entity.response.MailResPara;
import com.lst.model.MstClient;
import com.lst.model.MstMessage;
import com.lst.model.vo.MailVo;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: SendMailServlet
 * @Description: 邮件发送接口
 * @author zhangl
 * @date 2016年10月25日 上午11:34:44
 *
 */
public class SendMailServlet extends BaseServlet implements IMailServlet {

	private static final long serialVersionUID = 1L;

	private MstMessageMapper mstMessageMapper = ctx.getBean(MstMessageMapper.class);
	
	private MstClientMapper mstClientMapper = ctx.getBean(MstClientMapper.class);
	
	//private MstUserMapper mstUserMapper = ctx.getBean(MstUserMapper.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		MailResPara mailResPara = new MailResPara();

		try {
			MailReqPara mailReqPara = getReqPara(request);

			if(isCheckField(mailReqPara,mailResPara)){
				String userid = mailReqPara.getUserid();
				String mail = mailReqPara.getMail();
				String receivetype = mailReqPara.getReceivetype();
				String orderno = mailReqPara.getOrderno();
				
				String content = CommonUtils.getMail_model_order();
				
				if(!StringUtils.isEmpty(content)){
					
					String userName = "xx";
					if(CommCode.SYSCODE_MSG_TYPE_RECEIVE_USER.equals(Integer.valueOf(receivetype))){
						//MstUser mstUser = mstUserMapper.selectByPrimaryKey(Integer.valueOf(userid));
						//userName = mstUser.getNamecn();
						userName = "客服人员 ";
					} else if(CommCode.SYSCODE_MSG_TYPE_RECEIVE_CLIENT.equals(Integer.valueOf(receivetype))){
						MstClient mstClient = mstClientMapper.selectByPrimaryKey(Integer.valueOf(userid));
						userName = mstClient.getNamecn();
					} else {
						//code
					}
					
					content = content.replace("${V1}",userName);
					content = content.replace("${V2}",orderno);
					
					MailVo mailVo = new MailVo();
					mailVo.setFrom(CommonUtils.getSys_mail_account());
					mailVo.setRecipient(mail);
					mailVo.setSubject("[有点功夫]新订单通知！");
					mailVo.setContent(content);

					boolean flag = CommFun.sendMail(this,mailVo);
					
					if(flag){
						//将数据插入库
						MstMessage mstMessage = new MstMessage();
						mstMessage.setContent(mailVo.getContent());
						mstMessage.setCreatedate(startDate);
						mstMessage.setCreateuser(Integer.valueOf(userid));
						mstMessage.setEnabled(true);
						mstMessage.setIsdeleted(false);
						mstMessage.setReceiveid(Integer.valueOf(userid));
						mstMessage.setReceivetype(Integer.valueOf(receivetype));
						mstMessage.setSendid(-1);
						mstMessage.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_SYSTEM);
						mstMessage.setTitle("[有点功夫]新订单通知！");
						mstMessage.setType(CommCode.SYSCODE_MSG_TYPE_MAIL);
						
						mstMessageMapper.insert(mstMessage);
						
						mailResPara.setCode(CommCode.M_Y000000);
						mailResPara.setMessage(CommCode.M_Y000001);
					}else{
						mailResPara.setCode(CommCode.M_A000000);
						mailResPara.setMessage("激活失败");
					}
				}else{
					mailResPara.setCode(CommCode.M_A000000);
					mailResPara.setMessage(CommCode.M_O000008);
				}
			}

		} catch (Exception e) {
			mailResPara.setCode(CommCode.M_A000000);
			mailResPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().create();
			String jsonResult = gson.toJson(mailResPara);
			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			mailResPara.setCode(CommCode.M_A000000);
			mailResPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		MailReqPara mailReqPara = (MailReqPara) reqPara;
		MailResPara mailResPara = (MailResPara) resPara;

		if(StringUtils.isEmpty(mailReqPara.getUserid())){
			mailResPara.setCode(CommCode.M_A000000);
			mailResPara.setMessage(CommCode.M_P000002);
		} else if(StringUtils.isEmpty(mailReqPara.getMail())){
			mailResPara.setCode(CommCode.M_A000000);
			mailResPara.setMessage(CommCode.M_O000006);
		} else if(StringUtils.isEmpty(mailReqPara.getReceivetype())){
			mailResPara.setCode(CommCode.M_A000000);
			mailResPara.setMessage(CommCode.M_O000007);
		} else if(StringUtils.isEmpty(mailReqPara.getOrderno())){
			mailResPara.setCode(CommCode.M_A000000);
			mailResPara.setMessage(CommCode.M_E000013);
		} else{
			flag = true;
		}

		return  flag;
	}

	@Override
	public MailReqPara getReqPara(HttpServletRequest request) {
		MailReqPara mailReqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new MailReqPara());
			mailReqPara = (MailReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String mail = request.getParameter("mail");
			String receivetype = request.getParameter("receivetype");
			String orderno = request.getParameter("orderno");

			logger.info("reqPara userid: " + userid);
			logger.info("reqPara mail: " + mail);
			logger.info("reqPara receivetype: " + receivetype);
			logger.info("reqPara orderno:" + orderno); 
			
			mailReqPara.setUserid(userid);
			mailReqPara.setMail(mail);
			mailReqPara.setReceivetype(receivetype);
			mailReqPara.setOrderno(orderno);
			
		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return mailReqPara;
	}

	/**
	 * 子类自定义消息体
	 */
	@Override
	public Message getMessageBySession(Session session,MailVo mail) throws Exception{

		//邮件对象
		Message message = new MimeMessage(session);
		//设置发件人
		message.setFrom(new InternetAddress(mail.getFrom()));
		//设置收件人
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
		//设置邮件标题
		message.setSubject(mail.getSubject());
		//内容
		//message.setText("邮件内容！");
		message.setContent(mail.getContent(), "text/html;charset=UTF-8");
		//保存
		message.saveChanges();
		
		return message;
	}

}
